package com.njuse.jvmfinal.Instruction;

import java.nio.ByteBuffer;

import com.njuse.jvmfinal.memory.jclass.Field;
import com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.constant.ref.FieldRef;
import com.njuse.jvmfinal.runtimestructure.Jframe;
import com.njuse.jvmfinal.runtimestructure.Jobject;

public class GETFIELD extends Instruction {
	private int index;
	
	public  void readindex(ByteBuffer reader) {
		this.index=(int)reader.getShort();
	}
	
	public void execute(Jframe frame) {
		FieldRef fieldref=(FieldRef) frame.getMymethod().getClazz().getRuntimeConstantPool().getConstant(index);
		Field field=fieldref.findfield();
		String des=field.getDescriptor();
		int position=field.getPosition();
		Object[] managestack=frame.getManagestack();
		int top=frame.getStacktop();
		Jobject ref=(Jobject) managestack[top-1];
		Object[] fields=ref.getFields();
		top--;
        switch (des.charAt(0)) {
        case 'Z':
        case 'B':
        case 'C':
        case 'S':
        case 'I':
        case 'F':
        case 'L':
        case '[':	
            managestack[top]=fields[position];
            top++;
            break;
        case 'J':
        case 'D':
            managestack[top]=fields[position];
            managestack[top+1]=fields[position+1];
            top=top+2;
            break;
        }
        frame.setStacktop(top);
        frame.setManagestack(managestack);
	}
}
